package com.Auth;



import java.util.HashMap;
import java.util.Random;

// 验证码类
public class AuthCode {
    // 缓存<邮箱-验证码>的map
    private static HashMap<String, AuthObject> AUTHCODEMAP = null;

    public static void New(){
        // 初始化map
        AUTHCODEMAP = new HashMap<>();
        // 初始化AuthObject类
        AuthObject.New();
    }

    // 构造一个验证码对象，并返回对应的验证码
    public static int buildOneCodeAndReturn(String eMail){
        AuthObject authObject = new AuthObject(eMail);
        AUTHCODEMAP.put(eMail, authObject);
        return authObject.getAuthCode();
    }

    public static boolean isCorrect(String eMail, int code){
        if(!AUTHCODEMAP.containsKey(eMail)){
            return false;
        }
        return AUTHCODEMAP.get(eMail).isCorrect(code);
    }

}

// 验证码对象，方便管理一个验证码
class AuthObject{
    private static final int AuthTimeOutSeconds = 300; // 验证码过期时间300s
    private static Random random;
    private String eMail = "";
    // 6位数字验证码
    private int authCode = 0;
    private long buildSecond = 0;

    public static void New(){
        random = new Random();
    }

    public AuthObject(String _eMail){
        buildSecond = System.currentTimeMillis() / 1000;
        eMail = _eMail;
        // 随机一个6位数字
        authCode = random.nextInt(100000);
    }

    public int getAuthCode(){
        return authCode;
    }

    public boolean isCorrect(int code){
        if(buildSecond + AuthTimeOutSeconds < System.currentTimeMillis() / 1000){
            // 过期了
            return false;
        }
        return code == authCode;
    }
}
